package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysToken;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * Api 拦截, 检查token.
 *
 * @author ruoyi
 */
@Component
public class ApiInterceptor extends HandlerInterceptorAdapter
{

    @Autowired
    private ISysTokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String token = request.getHeader("token");

            if (StringUtils.isEmpty(token)){
                setResponse(response, ApiResult.tokenError("token 为空,请先获取token").toString());
                return false;
            }

            SysToken sysToken = new SysToken();
            sysToken.setToken(token);
            List<SysToken> tokenList = tokenService.selectSysTokenList(sysToken);
            if (tokenList.size() > 1 || tokenList.size() == 0){
                setResponse(response, ApiResult.tokenError("token 出现异常情况").toString());
                return false;
            }

            sysToken = tokenList.get(0);
            //判断token 是否过期
            Date date = new Date();
            Date experidDate = sysToken.getExpiredDate();
            if (experidDate != null && date.compareTo(experidDate) == 1){
                setResponse(response, ApiResult.tokenError("token 已经过期, 请重新登录").toString());
                return false;
            }

            //TODO 可做可不做 增加experidDate的过期时间 保证不过期

            return true;
        }
        else
        {
            return super.preHandle(request, response, handler);
        }
    }

    private void setResponse(HttpServletResponse response, String message){

        if (response == null){
            return;
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
